package io.itit.ecp.admin.provide.action.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.itit.ecp.admin.common.constants.ParamConstants;
import io.itit.ecp.admin.common.enums.StatisticsModeEnums;
import io.itit.ecp.admin.provide.action.req.DeviceMeterStatisticQueryDetailReq;
import io.itit.ecp.admin.provide.action.req.DeviceMeterStatisticQueryReq;
import io.itit.ecp.admin.provide.action.resp.DeviceMeterStatisticsResp;
import io.itit.ecp.admin.provide.filter.IEnergyDataFilter;
import io.itit.ecp.admin.provide.helper.SceneHelper;
import io.itit.ecp.admin.server.entity.extend.EnergyDataExtEntity;
import io.itit.ecp.admin.server.service.IEnergyDataService;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.provide.action.validation.IExport;
import io.itit.grass.common.provide.action.validation.IQueryPage;
import io.itit.grass.common.provide.utils.ParamUtils;
import io.itit.grass.common.server.dto.ParamDto;
import io.itit.grass.common.server.utils.ConvertUtils;
import io.itit.grass.estelle.starter.core.ExcelXSSFUtil;
import io.itit.grass.estelle.starter.util.JsonUtil;
import io.itit.grass.web.wall.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：计量统计控制类
 * @Date：Create by 2023-12-05 11:48:22
 */
@Api(tags = "设备计量统计")
@RestController
@RequestMapping("/ecp-admin/deviceMeterStatistic")
public class DeviceMeterStatisticController {

    @Resource
    private IEnergyDataService energyDataService;

    @ApiOperation("设备计量统计分页查询")
    @PostMapping("queryPage")
    @RequiresPermissions("ecp-admin:deviceMeterStatistic:search")
    public ResultResp<IPage<DeviceMeterStatisticsResp>> queryPage(@RequestBody @Validated(IQueryPage.class) DeviceMeterStatisticQueryReq req) {
        ParamDto paramDto = ParamUtils.paramDto(req);
        if (!"hour".equals(req.getStatisticsMode())) {
            if (!paramDto.containsKey("solidifyDateStart")) {
                paramDto.add("solidifyDateStart", LocalDateTime.now().minusHours(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            paramDto.add(ParamConstants.MYSQL_DATE_FORMAT, StatisticsModeEnums.mysqlDateFormat(req.getStatisticsMode()));
        } else {
            if (!paramDto.containsKey("solidifyDateStart")) {
                paramDto.add("solidifyDateStart", LocalDateTime.now().minusHours(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
        }
        if ("day".equals(req.getStatisticsMode()) && !paramDto.containsKey("solidifyDateStart")) {
            paramDto.add("solidifyDateStart", LocalDate.now().atTime(LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        IPage<EnergyDataExtEntity> page = energyDataService.deviceMeterStatistics(paramDto,
                PageUtils.getPage(req, EnergyDataExtEntity.class));
        return ResultResp.success(SceneHelper.i().setSceneInfo(ConvertUtils.convert(page, DeviceMeterStatisticsResp.class)));
    }

//    @ApiOperation("读数详情")
//    @PostMapping("queryDetail")
//    @RequiresPermissions("ecp-admin:deviceMeterStatistic:search")
//    public ResultResp<IPage<DeviceMeterStatisticsResp>> queryDetail(@RequestBody @Validated(IQueryPage.class) DeviceMeterStatisticQueryDetailReq req) {
//
//        IPage<EnergyDataExtEntity> page = energyDataService.deviceMeterDetailStatistics(ParamUtils.paramDto(req)
//                        .add(ParamConstants.MYSQL_DATE_FORMAT, StatisticsModeEnums.mysqlDateFormat(req.getStatisticsMode())),
//                PageUtils.getPage(req, EnergyDataExtEntity.class));
//        return ResultResp.success(SceneHelper.i().setSceneInfo(ConvertUtils.convert(page, DeviceMeterStatisticsResp.class)));
//    }

    @ApiOperation("导出")
    @PostMapping("export")
    @RequiresPermissions("ecp-admin:energyData:export")
    public void export(@RequestBody @Validated(IExport.class) DeviceMeterStatisticQueryReq req, HttpServletResponse response) {
        List<EnergyDataExtEntity> list = energyDataService.deviceMeterExport(ParamUtils.paramDto(req)
                .add(ParamConstants.MYSQL_DATE_FORMAT, StatisticsModeEnums.mysqlDateFormat(req.getStatisticsMode())));
        ExcelXSSFUtil.export("DeviceMeterStatisticsExport", JsonUtil.toJson(list, new IEnergyDataFilter.EnergyDataExtExportFilter()), response);
    }

    public void checkDetailReq(DeviceMeterStatisticQueryDetailReq req) {
        String mysqledDateFormat = StatisticsModeEnums.javaDateFormat(req.getStatisticsMode());
        if (StringUtils.isNotBlank(req.getSolidifyDateStr())) {
            SimpleDateFormat dateFormat = new SimpleDateFormat(mysqledDateFormat);
            Date solidifyDate;
            try {
                solidifyDate = dateFormat.parse(req.getSolidifyDateStr());
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            if (StatisticsModeEnums.day.mode.equals(req.getStatisticsMode())) {
                req.setSolidifyDateStart(DateUtil.formatDateTime(solidifyDate));
                req.setSolidifyDateEnd(DateUtil.formatDateTime(DateUtil.endOfDay(solidifyDate)));
            } else if (StatisticsModeEnums.month.mode.equals(req.getStatisticsMode())) {
                req.setSolidifyDateStart(DateUtil.formatDateTime(solidifyDate));
                req.setSolidifyDateEnd(DateUtil.formatDateTime(DateUtil.endOfMonth(solidifyDate)));
            } else if (StatisticsModeEnums.year.mode.equals(req.getStatisticsMode())) {
                req.setSolidifyDateStart(DateUtil.formatDateTime(solidifyDate));
                req.setSolidifyDateEnd(DateUtil.formatDateTime(DateUtil.endOfYear(solidifyDate)));
            } else {
                throw new RuntimeException();
            }
        }
    }

}
